#include <func.h>

int main ()
{
int SemArrid = semget(10000,2,IPC_CREAT|0600);
ERROR_CHECK(SemArrid,-1,"semget");
unsigned short arr[2]= {0,10};
int ret = semctl(SemArrid,0,SETALL,arr);
ERROR_CHECK(ret,-1,"semctl");
if(!fork())
{
   struct sembuf consume[2];
   consume[0].sem_num = 0;
   consume[0].sem_flg = SEM_UNDO;
   consume[0].sem_op = -1;//商品数减少1；
   consume[1].sem_num = 1;
   consume[1].sem_flg = SEM_UNDO;
   consume[1].sem_op = 1;//空格加1；
   while(1)
   {
    sleep(2);
    printf("I am consumer, before consume,product = %d, space =%d\n",
    semctl(SemArrid,0,GETVAL),semctl(SemArrid,1,GETVAL));
    semop(SemArrid,&consume[0],1);
    printf("Buy a product\n");
    semop(SemArrid,&consume[1],1);
    printf("I am consumer, after consume,product = %d, space =%d\n",
    semctl(SemArrid,0,GETVAL),semctl(SemArrid,1,GETVAL));
    
   }
exit(0);
   

}
else
{
struct sembuf product[2];
product[0].sem_num = 0;
product[0].sem_flg = SEM_UNDO;
product[0].sem_op =1;//商品加1；
product[1].sem_num = 1;
product[1].sem_flg = SEM_UNDO;
product[1].sem_op =-1;//空格减1
while(1)
{

printf("I am producer,before produce,product = %d,apace=%d\n",
     semctl(SemArrid,0,GETVAL),semctl(SemArrid,1,GETALL));
semop(SemArrid,&product[0],1);
printf("produce a procuct\n");
semop(SemArrid,&product[1],1);
printf("I am producer,after produce,product = %d,apace=%d\n",
     semctl(SemArrid,0,GETVAL),semctl(SemArrid,1,GETALL));
}
wait(NULL);



}

    return 0;
}